using UnityEngine;

public class Parabola
{
    public float Distance { get; private set; }
    private float _a;
    private float _b;
    private float _c;
    private Vector3 _start;
    private Quaternion _q;
    public Parabola()
    {

    }
    public void Set(Vector3 start, Vector3 end, float height)
    {
        _start = start;
        end -= start;
        start = Vector3.zero;
        var a = start;
        var b = end;
        a.y = b.y = 0;
        this.Distance = Vector3.Distance(a, b);
        _q = Quaternion.LookRotation((b - a).normalized, Vector3.up);
        height -= _start.y;
        end.x = Distance;
        // 起点和终点降维
        var x1 = start.x; //起始点
        var y1 = start.y;
        var x3 = end.x;//终点
        var y3 = end.y;
        var xinc = end.x - start.x;
        //算出中间会经过的一点
        var x2 = x1 + xinc * 0.5f;
        var y2 = height;

        //根据抛物线方程ax^2+bx+c=y，得方程组 //ax1^2+bx1+c=y1 //ax2^2+bx2+c=y2 //ax3^2+bx3+c=y3 //解方程组
        _b = ((y1 - y3) * (x1 * x1 - x2 * x2) - (y1 - y2) * (x1 * x1 - x3 * x3)) / ((x1 - x3) * (x1 * x1 - x2 * x2) - (x1 - x2) * (x1 * x1 - x3 * x3));
        _a = ((y1 - y2) - _b * (x1 - x2)) / (x1 * x1 - x2 * x2);
        _c = y1 - _a * x1 * x1 - _b * x1;
    }
    public Vector3 GetPointByDistance(float distance)
    {
        var x = distance;
        var y = _a * x * x + _b * x + _c;
        var f = Vector3.forward * x;
        //升维
        f = _q * f;
        f.y = y;
        return f + _start;
    }
    public Vector3 GetPointByProgress(float value)
    {
        return GetPointByDistance(this.Distance * value);
    }
}